/**
 * Copyright (c) 2013-2016, Jieven. All rights reserved.
 *
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
 * To use it on other terms please contact us at 1623736450@qq.com
 */
package com.jobsys.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.JobKey;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jobsys.model.Task;
import com.jobsys.quartz.QuartzPlugin;

/**
 * 定时任务
 * 
 * @author Jieven
 * 
 */
public class TaskController extends Controller {
	private Logger logger = Logger.getLogger(TaskController.class);

	public void index() {
		render("/login.jsp");
	}

	// 查询任务
	public void queryAllTask() {
		String page = this.getPara("pageNumber");
		String pagesize = this.getPara("pageSize");
		List<Task> tasks = Task.dao.findAll(Integer.parseInt(page), Integer.parseInt(pagesize));
		int count = Task.dao.Count();

		JSONObject json = new JSONObject();
		json.put("rows", tasks);
		json.put("total", count);

		renderJson(json);
	}

	// 修改任务
	public void updateTask() {
		try {
			int id = this.getParaToInt("id");
			String exp = this.getPara("exp");
			int state = this.getParaToInt("state");
			String name = this.getPara("name");
			String info = this.getPara("info");

			boolean isRight = org.quartz.CronExpression.isValidExpression(exp);
			String re = "";
			if (isRight) {
				Task.dao.updateTask(id, exp, state, name, info);
				re = "更新成功！";
			} else {
				re = "表达式错误";
			}

			JSONObject json = new JSONObject();
			json.put("msg", re);

			this.renderJson(json);
		} catch (Exception ex) {
			System.out.println(ex);
			this.render("./except.html");
		}
	}

	// 启动任务
	public void start() {
		int id = getParaToInt(0);

		Task task = Task.dao.findById(id);

		try {
			String className = task.getStr("clazz");

			// 恢复任务
			JobKey jobKey = JobKey.jobKey(className, className);
			QuartzPlugin.scheduler.resumeJob(jobKey);

			Task.dao.updateState(id, Task.STATE_START);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("启动失败");
		}

		logger.info("启动成功");
	}

	// 暂停任务
	public void stop() {
		int id = getParaToInt(0);

		Task task = Task.dao.findById(id);

		try {
			String className = task.getStr("clazz");

			// 暂停任务
			JobKey jobKey = JobKey.jobKey(className, className);
			QuartzPlugin.scheduler.pauseJob(jobKey);

			Task.dao.updateState(id, Task.STATE_STOP);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("停止失败");
		}

		logger.info("停止成功");
	}

	// 立即运行一次任务
	public void trigger() {
		int id = getParaToInt(0);

		Task task = Task.dao.findById(id);

		try {
			String className = task.getStr("clazz");

			// 立即触发一次
			JobKey jobKey = JobKey.jobKey(className, className);
			QuartzPlugin.scheduler.triggerJob(jobKey);

		} catch (Exception e) {
			e.printStackTrace();
			logger.info("任务执行一次失败");
		}

		logger.info("任务执行一次成功");
	}

}